<template>
  <div>
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
    <el-tree
      class="filter-tree"
      :data="data"
      :props="defaultProps"
      default-expand-all
      :filter-node-method="filterNode"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
export default {
  data() {
    return {
      filterText: "",
      deps: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dep: {
        name: "",
        parentId: -1,
      },
      pname: "",
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    //删除方法
    deleteDate(data) {
      if (data.isparent) {

      } else {
        this.$confirm("是否删除", {
          confirmButtonText: "yes",
          cancelButtonText: "no",
        }).then(() => {
          this.deleteRequest("url" + data.id).then((resp) => {
            if (resp) {
              this.removeDepFROMdeps(null,this.deps, data.id);
            }
          });
        });
      }
    },
    removeDepFROMdeps(p,deps,id){
        for(let i =0; i<deps.length; i++){
            let d =deps[i]
            if(d.id == id){
                deps.splice(i,1)
                if(deps.length == 0){
                    p.isparent = false
                }
                return 
            }else{
                this.removeDepFROMdeps(d,d.children,id)
            }
        }
    },
    initDep() {
      this.dep = {
        name: "",
        parentId: -1,
      };
    },
    addDep2Deps(deps, dep) {
      for (let i = 0; i < deps.length; i++) {
        let d = deps[i];
        if (d.id == dep.parentId) {
          d.children.concant(dep);
          if(d.children.length >0){
              d.isparent = true
          }
          return;
        } else {
          this.addDep2Deps(d.children, dep);
        }
      }
    },
    doAddDep() {
      this.postRequest("url", this.dep).then((resp) => {
        if (resp) {
          //手动插入
          this.addDep2Deps(this.deps, resp.obj);
          this.initDeps();
        }
      });
    },

    showAddDep(data) {
      this.dep.parentId = data.id;
      this.pname = data.name;
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
  },
};
</script>

<style>
</style>